function export_analysis(varargin)
%
% Write analysis results from a selected structure in the control
% worksheet.
% This routine finds all of the elements of the selected structure in
% and prints a comma-separated table of the results that can be copied and
% imported into Excel, Prism, or Igor Pro
%
% 1/15/02 P. Manis.
%
% Call: WIth no arguments, find the GUI figure and display it with all
% known from the CONTROL database listed

global CONTROL
if(nargin == 0)  % create list box and see what's up
    hf = findobj('tag', 'Export');
    if(isempty(hf))
        open('export_analysis_fig.fig');
    else
        figure(hf);
    end;

    l = length(CONTROL); % select all.
    nv = 0;
    fns = fieldnames(CONTROL);
    valid_s = cell(length(fns), 1); % preallocate for max possible
    sf = getmainselection;
    for i = 1:length(fns)
        for j = sf
            fn = sprintf('CONTROL(%d).%s', j, char(fns(i)));
            if(isstruct(eval(fn)))
                nv = nv + 1;
                valid_s{nv} = char(fns(i));
                %fprintf('STRUCT: %s\n', char(fns(i)));
            end;
        end;
    end;
    v={};
    nv = 0;
    for ni = 1:length(valid_s)
        if(~isempty(valid_s{ni}))
            nv = nv+1;
            v{nv} = valid_s{ni};
        end;
    end;
    valid_s = unique(v); % reduce list to unique values...
    hlist = findobj('tag', 'Export_listbox');
    set(hlist, 'string', valid_s);
    return;
end;

% if there is at least one argument, we will fall through to here

switch(varargin{1})  % parse commands!!!
    case {'reload'}

        l = length(CONTROL); % select all.
        sf = getmainselection;
        if(sf == 0)
            return;
        end;
        nv = 0;
        fns = fieldnames(CONTROL);
        valid_s = cell(length(fns), 1);
        for i = 1:length(fns)
            for j = sf
                fn = sprintf('CONTROL(%d).%s', j, char(fns(i)));
                if(isstruct(eval(fn)))
                    nv = nv + 1;
                    valid_s{nv} = char(fns(i));
                    %fprintf('STRUCT: %s\n', char(fns(i)));
                end;
            end;
        end;
        v={};
        nv = 0;
        for ni = 1:length(valid_s)
            if(~isempty(valid_s{ni}))
                nv = nv+1;
                v{nv} = valid_s{ni};
            end;
        end;
        valid_s = unique(v); % reduce list to unique values...        valid_s = sort(valid_s); % sort the list alphabetically
        hlist = findobj('tag', 'Export_listbox'); % then put it in the listbox
        set(hlist, 'string', valid_s);

    case {'exit', 'cancel'} % all done...
        h = findobj('tag', 'Export');
        close(h);
        return;
    case {'proceed'} % write the result.
        fout = 1;
        chk = findobj('tag', 'Export_chkfileout');
        if(ishandle(chk))
            fchk = get(chk, 'Value');
            if(fchk == 1)
                fext = {'.txt'; '.dat'};
                [f p filter] = uiputfile('*.txt', 'Output File', [pwd '/export']);
                if (f == 0)
                    return;
                end;
                fout = fopen([p f fext{filter}], 'w');
                if(fout == -1)
                    fprintf(1, 'Export_analysis: could not open file %s for output\n', ...
                        [p f]);
                    return;
                end;

            end;
        end;

        sf = getmainselection;
        hst = findobj('tag', 'Export_listbox');
        i = get(hst, 'value');
        fns = get(hst, 'string');
        listvals(CONTROL, sf, fns(i), fout);
        if(fout ~= 1)
            fclose(fout);
        end;

    otherwise
        fprintf(1, 'Export_Analysis: ?unrecognized command: %s\n', varargin{1});
        return;
end;


function listvals(ctl, sflist, fn, fout)
% write out the values in the structure for one entry
% first line is the names of the elements of the structure that can be written.
% only elements that are not structures or arrays themselves can be written.
% i.e., length of 1 and not structure.


cs=char('-'+zeros(1, 80));
sep = ','; % comma separated - 0r use tab sep...

x = eval(sprintf('ctl(%d).%s', sflist(1), char(fn))); % get the structure
if(~ isempty(x) && isstruct(x))
    fnx = fieldnames(x); % find the fields.
else
    fprintf(1, 'No structure %s in list????\n', char(fn))
    return;
end

fnx = sort(fnx); % put them alphabetically
valid_f = [];
for i = 1:length(fnx)
    try
        a = eval(sprintf('x.%s', char(fnx(i))));
        if(~isstruct(a) && length(a) == 1)
            valid_f = [valid_f i]; % just save the valid fields
        end;
    catch
    end;
end;
if(isempty(valid_f))
    return;
end;

% write the header out first
if(fout == 1)
    fprintf(fout, '\n%s\n', cs);
end;
fprintf(fout, '%s%s', char(fn), sep);
fprintf(fout, '%s%s%s%s%s%s%s%s%s%s%s','pnd', sep, 'div', sep, 'E_C', ...
    sep, 'G1', sep, 'G2', sep, 'Vm');
for i = valid_f
    fprintf(fout, '%s%s', sep,char(fnx(i)));
end;
fprintf(fout, '\n');

for i = 1: length(sflist)
    sf = sflist(i);
    fprintf(fout, '%s%s ', ctl(sf).filename, sep); % first the filename and the structure
    if(~isempty(ctl(sf).pnd))
        fprintf(fout, '%s%s ', num2str(ctl(sf).pnd), sep);
    else
        fprintf(fout, '%s%s ', '0', sep);
    end;

    % always list the tagged fields for sorting and selecting
    if(~isempty(ctl(sf).div))
        fprintf(fout, '%s%s ', num2str(ctl(sf).div), sep);
    else
        fprintf(fout, '%s%s ', '0', sep);
    end;
    if(~isempty(ctl(sf).E_C))
        fprintf(fout, '%s%s ', num2str(ctl(sf).E_C), sep);
    else
        fprintf(fout, '%s%s ', '0', sep);
    end;
    if(~isempty(ctl(sf).G1))
        fprintf(fout, '%s%s ', num2str(ctl(sf).G1), sep);
    else
        fprintf(fout, '%s%s ', '0', sep);
    end;
    if(~isempty(ctl(sf).G2))
        fprintf(fout, '%s%s ', num2str(ctl(sf).G2), sep);
    else
        fprintf(fout, '%s%s ', '0', sep);
    end;
    fprintf(fout, '%7.2f', ctl(sf).Rmp); % and always list the rmp

    % now for all the fields of the structure, list those which
    % are numeric. Skip those that are either other structures or arrays
    %
    x = eval(sprintf('ctl(%d).%s', sf, char(fn))); % get the structure
    if(isempty(x))
        fprintf (fout, ' <no %s data in this file>\n', char(fn));
    else
        for j = valid_f
            u = eval(sprintf('x.%s', char(fnx(j))));
            if(isnumeric(u))
                if(isnan(u))
                    fprintf(fout, '%s ', sep);
                else
                    fprintf(fout, '%s%f', sep, u);
                end;
            else
                fprintf(fout, '%s%s', sep, u);
            end;
        end;
        fprintf(fout, '\n');
    end
end;
if(fout ~= 1)
    fprintf(fout, '%s\n', cs);
end;

